﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Nivot.PowerShell.WindowsMobile.Rapi2;

namespace Nivot.PowerShell.WindowsMobile
{
    public class CEProxyController
    {
        private readonly RemoteDevice _device;

        internal CEProxyController(RemoteDevice device)
        {
            _device = device;
        }

        internal string CEProxyPath
        {
            get { return Path.Combine(_device.GetTempPath(), "CEProxy.exe"); }
        }

        internal void ShellEx(string fullPath)
        {
            EnsureCEProxy();

            Provider.WriteVerbose(String.Format("Invoking {0} on remote device.", fullPath));
            
            // try to invoke image on device
            string args = String.Format("shellex \"{0}\"", fullPath);
            _device.CreateProcess(CEProxyPath, args, ProcessCreationFlags.None);
        }

        internal void EnsureCEProxy()
        {
            try
            {
                CEFileAttributes attributes = _device.GetFileAttributes(CEProxyPath);
            }
            catch (RapiException ex)
            {
                Provider.WriteVerbose("No CEProxy found.");
                InstallCEProxy();
            }
        }

        internal void InstallCEProxy()
        {            
            string basePath = Provider.ProviderInfo.PSSnapIn.ApplicationBase;
            string sourcePath = Path.Combine(basePath, Path.GetFileName(CEProxyPath));
            Provider.WriteVerbose(sourcePath);
            try
            {
                _device.CopyFileToDevice(sourcePath, CEProxyPath, true);
                Provider.WriteVerbose("Successfully copied CEProxy to device.");
            }
            catch (RapiException ex)
            {
                Provider.WriteWarning("Unable to copy CEProxy to device: " + ex.Message);
            }
        }

        internal void UninstallCEProxy()
        {
            try
            {
                _device.DeleteFile(CEProxyPath);
                Provider.WriteVerbose("Successfully removed CEProxy from device.");
            }
            catch (RapiException ex)
            {
                Provider.WriteWarning("Unable to remove CEProxy from device: " + ex.Message);
            }
        }

        internal static WindowsMobileProvider Provider
        {
            get { return (WindowsMobileProvider)StoreProviderContext.Current; }
        }
    }
}
